package com.wanyangproject.my;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.wanyangproject.R;
import com.wanyangproject.entity.BianJiFangKeEntity;
import com.wanyangproject.fuwuactivity.TianJiaFangKeActivity;
import com.wanyangproject.popuwindow.ShareTuOianPopupWindow;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.JieShuYeMian;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class MyBianJiFangKeActivity extends AppCompatActivity implements JieShuYeMian {


    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_daofang_renshu)
    EditText etDaofangRenshu;
    @BindView(R.id.et_chepaihao)
    EditText etChepaihao;
    @BindView(R.id.btn_xiugai)
    Button btnXiugai;
    @BindView(R.id.tv_daofang_shijian)
    TextView tvDaofangShijian;
    private String name;
    private String number;
    private String phone;
    private String daodatime;
    private String chapai;
    private String id;
    private Dialog dialogtishi;
    private BianJiFangKeEntity bianJiFangKeEntity;
    private ImageView imageTanchuang;
    private ShareTuOianPopupWindow shareTuOianPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_bian_ji_fang_ke);
        ButterKnife.bind(this);

//
//        intent.putExtra("name",fangKeGuanLiEntity.getResponse().get(position).getName());
//        intent.putExtra("number",fangKeGuanLiEntity.getResponse().get(position).getNums());
//        intent.putExtra("phone",fangKeGuanLiEntity.getResponse().get(position).getPhone());
//        intent.putExtra("daodatime",fangKeGuanLiEntity.getResponse().get(position).getDaodaTime());
//        intent.putExtra("chapai",fangKeGuanLiEntity.getResponse().get(position).getChepai());

        Intent intent = getIntent();
        name = intent.getStringExtra("name");
        number = intent.getStringExtra("number");
        phone = intent.getStringExtra("phone");
        daodatime = intent.getStringExtra("daodatime");
        chapai = intent.getStringExtra("chapai");
        id = intent.getStringExtra("id");


        if (name != null) {
            etName.setText(name);
        }

        if (number != null) {
            etDaofangRenshu.setText(number);
        }


        if (phone != null) {
            etPhone.setText(phone);
        }

        if (daodatime != null) {
            tvDaofangShijian.setText(daodatime);
        }

        if (chapai != null) {
            etChepaihao.setText(chapai);
        }


    }



    @OnClick({R.id.image_back, R.id.et_name, R.id.et_phone, R.id.et_daofang_renshu, R.id.tv_daofang_shijian, R.id.et_chepaihao, R.id.btn_xiugai})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.et_name:
                break;
            case R.id.et_phone:
                break;
            case R.id.et_daofang_renshu:
                break;
            case R.id.tv_daofang_shijian:
                Calendar calendar = Calendar.getInstance();

                TimePickerView timePickerView = new TimePickerView.Builder(MyBianJiFangKeActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        tvDaofangShijian.setText(simpleDateFormat1.format(date));
//                        try {
//                            Date date1 = simpleDateFormat1.parse(tvTime.getText().toString());
//                            long time = date1.getTime();
//                            string = String.valueOf(time);
//                            System.out.println(string + "     时间戳");
//                        } catch (ParseException e) {
//                            e.printStackTrace();
//                        }
                    }
                })
                        .setType(new boolean[]{true, true, true, true, true, false})//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setTextXOffset(0, 0, 0, 0, 0, 0)
                        .setLunarCalendar(false)
                        .setContentSize(14)//滚轮文字大小
                        .gravity(Gravity.CENTER)
                        .setLineSpacingMultiplier(2.8f)//设置两横线之间的间隔倍数
                        .setTitleSize(16)//标题文字大小
                        .setTitleText("到访时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(false)//是否循环滚动
                        .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                        .setTextColorOut(Color.parseColor("#AEAAAA"))
                        .setTitleColor(Color.BLACK)//标题文字颜色
                        .setSubmitColor(Color.RED)//确定按钮文字颜色
                        .setCancelColor(Color.parseColor("#AEAAAA"))//取消按钮文字颜色
                        .setTitleBgColor(Color.parseColor("#f5f5f5"))//标题背景颜色 Night mode
                        .setBgColor(Color.parseColor("#ffffff"))//滚轮背景颜色 Night mode
                        .setRange(calendar.get(Calendar.YEAR), 2100)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
                        .setLabel("年", "月", "日", ":", "", "")
                        .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .isDialog(false)//是否显示为对话框样式
                        .build();
                timePickerView.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                timePickerView.show();


                break;
            case R.id.et_chepaihao:
                break;
            case R.id.btn_xiugai:

                Calendar instance = Calendar.getInstance();

                int year = instance.get(Calendar.YEAR);
                int month = instance.get(Calendar.MONTH)+1;// 获取当前月份
                int day = instance.get(Calendar.DAY_OF_MONTH);// 获取当日期
                int hour = instance.get(Calendar.HOUR_OF_DAY);//日
                int minute = instance.get(Calendar.MINUTE);//时
                int miao = instance.get(Calendar.SECOND);//分
                System.out.println(month+"      month");
                System.out.println(day+"      day");
                System.out.println(hour+"       hour");
                System.out.println(minute+"         minute");
                System.out.println(miao+"         miao");
                System.out.println(tvDaofangShijian.getText().toString().trim()+"         tvTime");


                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    Date date = sdf.parse(tvDaofangShijian.getText().toString().trim());
                    System.out.println(date+"    date");
                    System.out.println(date.getTime()+"            date.getTime()");
//                    Date date1 = sdf.parse(year+"-"+month+"-"+day+" "+hour+":"+minute+":"+miao);
                    Date date1 = sdf.parse(year+"-"+month+"-"+day+" "+hour+":"+minute);
                    System.out.println(year+"-"+month+"-"+day+" "+hour+":"+minute+"         时间时间");

//                    输入框时间            系统时间
                    if(date.getTime() <= date1.getTime()){
                        Toast.makeText(this, "请输入正确的时间！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }


//                修改访客信息的网络请求
                initXiuGaiFangKeXinXiHttp();
                break;
        }
    }







    //    修改访客信息的网络请求
    private void initXiuGaiFangKeXinXiHttp() {
        if (ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim()) == false) {
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim());

        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "dengji/viewdengji")
                .addHeader("token", ContractUtils.getTOKEN(MyBianJiFangKeActivity.this))
                .addParams("parkId", ContractUtils.getParkId(MyBianJiFangKeActivity.this))
                .addParams("name", etName.getText().toString().trim())
                .addParams("phone", etPhone.getText().toString().trim())
                .addParams("nums", etDaofangRenshu.getText().toString().trim())
                .addParams("chepai", etChepaihao.getText().toString().trim())
                .addParams("daodaoTime", tvDaofangShijian.getText().toString().trim())
                .addParams("id",id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response+"        修改访客信息的网络请求 ");
                        ContractUtils.Code500(MyBianJiFangKeActivity.this,response);
                        if(response.indexOf("200") != -1){
                            Gson gson = new Gson();
                            bianJiFangKeEntity = gson.fromJson(response, BianJiFangKeEntity.class);
                            Toast.makeText(MyBianJiFangKeActivity.this, bianJiFangKeEntity.getMsg(), Toast.LENGTH_SHORT).show();
                            TanChuang();
//                            finish();
                        }else{
                            ContractUtils.Code400(MyBianJiFangKeActivity.this,response);
                        }
                    }
                });

    }





    //    二维码提示框
    private void TanChuang() {
//        弹出二维码
        dialogtishi = new Dialog(this, R.style.Theme_Light_Dialog);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.tianjiefangke_erweima, null);
        Window window = dialogtishi.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.CENTER);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        window.setWindowAnimations(R.style.dialogStyle);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        dialogtishi.setContentView(dialogView);
        dialogtishi.show();

        imageTanchuang = dialogtishi.getWindow().findViewById(R.id.image_tanchuang);
        if (ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + bianJiFangKeEntity.getResponse().getPhoto() == null) {

        } else {
            Glide.with(MyBianJiFangKeActivity.this).load(ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + bianJiFangKeEntity.getResponse().getPhoto()).into(imageTanchuang);
        }


//        Drawable drawable = getResources().getDrawable(R.mipmap.logo);
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);

        Object itemsOnClick = null;
        shareTuOianPopupWindow = new ShareTuOianPopupWindow(MyBianJiFangKeActivity.this,(View.OnClickListener) itemsOnClick);
        shareTuOianPopupWindow.setIsOK(ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + bianJiFangKeEntity.getResponse().getPhoto());
        shareTuOianPopupWindow.setTupian(ContractUtils.YUANQUZHAOSHANG_PHOTO_URL+"/"+bianJiFangKeEntity.getResponse().getLogo());
        System.out.println(ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + bianJiFangKeEntity.getResponse().getPhoto()+"    图片链接");
        shareTuOianPopupWindow.setJieShuYeMian(this);


        dialogtishi.getWindow().findViewById(R.id.tv_fenxiang).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogtishi.dismiss();
                shareTuOianPopupWindow.showAtLocation(findViewById(R.id.relative_Layout), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        });



        dialogtishi.getWindow().findViewById(R.id.tv_duanxin).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialogtishi.dismiss();
                        //                判断当前SDK版本号
                        if (Build.VERSION.SDK_INT >= 23) {
//                    当前拨打电话权限是没有给的
                            if (ContextCompat.checkSelfPermission(MyBianJiFangKeActivity.this, Manifest.permission.RECEIVE_MMS) != PackageManager.PERMISSION_GRANTED) {
//                        我要请求权限
                                ActivityCompat.requestPermissions(MyBianJiFangKeActivity.this, new String[]{Manifest.permission.RECEIVE_MMS}, 1);
                            } else {
//                        ShareUtils.shareshortmessage(share_title,ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto(),share_desc,share_img,platformActionListener);
                                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"));
                                intent.putExtra("sms_body", ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + bianJiFangKeEntity.getResponse().getPhoto());
                                startActivity(intent);
                            }
                        } else {
//                    ShareUtils.shareshortmessage(share_title,ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + tianjiaFangkeEntity.getResponse().getPhoto(),share_desc,share_img,platformActionListener);
                            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"));
                            intent.putExtra("sms_body", ContractUtils.YUANQUZHAOSHANG_PHOTO_URL + "/" + bianJiFangKeEntity.getResponse().getPhoto());
                            startActivity(intent);
                        }
                    }
                });
    }

    @Override
    public void jieshu() {
        finish();
    }
}
